<?php
session_start();
$hostname="mysql-user.cse.msu.edu"; // Host name
$username="hewittry"; // Mysql username
$password="A39777266"; // Mysql password
$database="hewittry"; // Database name
$currPage = "search";
include("inc_header.php");

?>
<div id="content">
<?

	if (isset($_POST['delete']))
	{
		$id = (int)$_REQUEST["id"];
		if ($_SESSION["usertype"] != "admin")
		{

		  $query = "SELECT Photo FROM VehicleForSale WHERE NonAdmins_AllUsers_LogonID = '" . $_SESSION['username'] . "' AND VehicleForSaleID = " . $id;
			$result = mysql_query($query); 

			if (mysql_num_rows($result))
			{
				$row = mysql_fetch_assoc($result);
				$query = "DELETE FROM VehicleForSale WHERE VehicleForSaleID = " . $id;
				$result = mysql_query($query); 
				unlink("upload/" . $row['Photo']);

			?>

				<h2>Post deleted.</h2>
			<?php
			}
		}
		else
		{
			$query = "DELETE FROM VehicleForSale WHERE VehicleForSaleID = " . $id;
			$result = mysql_query($query);
		?>

			<h2>Post deleted.</h2>
		<?php
		}
		
		?>

	<?php
	}
	else
	{
		$id = (int)$_REQUEST["id"];
		if (!is_int($id)) { die("Error: Invalid id number."); }
		
		$conn = new mysqli($hostname, $username, $password, $database);
		
		/*if(isset($_REQUEST['submit']))
		{
			$comment = $conn->real_escape_string($_REQUEST['comment']);
			$query = "INSERT INTO Comments VALUES ('" . $_SESSION['username'] . "', $id, " . time() . ", '$comment')";
			$result = $conn->query($query);
		}*/
		
		$query = "SELECT * FROM VehicleForSale WHERE VehicleForSaleID = " . $id;
		$result = $conn->query($query);
		if ($result->num_rows == 0) { die ("Error: no record found."); }
		$row = $result->fetch_assoc();
	?>

	
		<h2><a href="#"><?php echo $row["Make"] . " " . $row["Model"] . " " . $row["VehicleYear"]; ?></a></h2>
	<?php
		// If an admin is logged in, give them the ability to delete this car
		if ($_SESSION['usertype'] == "admin")
		{
	?>
		<form method="post" action="viewCar.php?id=<?php echo $id; ?>" enctype="multipart/form-data">
		<table>
			<tr>
			<td>&nbsp;</td>
			<td><input type="submit" value="Delete Announcement" name="delete" id="delete" /></td>
			</tr>
		</table>
		</form>
		<br /><br />

	<?php
		}
	?>
		<table>
		
			<tr>
				<td style="padding-right: 10px; padding-top: 15px; vertical-align: top;">
					<img src="./upload/<?php echo $row["Photo"];?>" style="height: 200px; width: 200px;" />
					<?php
						if ($_SESSION["usertype"] == "regular" && $_SESSION["username"] != $row["NonAdmins_AllUsers_LogonID"])
						{
							echo "<br /><a href='#' onclick='send(1); return false;'>Send Notification</a> | ";
							echo "<a href='#' onclick='send(2); return false;'>Bookmark</a>";
						}
					?>
					<br />
				</td>
				<td>
					<strong>Basic Information</strong><br />
					<table style="padding: 10px;">
						<tr>
							<td>Item #:</td>
							<td><?php echo $row["VehicleForSaleID"];
									$carId = $row["VehicleForSaleID"]; ?></td>
						</tr>
						<tr>
							<td>Price:</td>
							<td>$<?php echo $row["Price"]; ?></td>
						</tr>
						<tr>
							<td>Owner:</td>
							<td><?php echo $row["NonAdmins_AllUsers_LogonID"]; $carSeller = $row["NonAdmins_AllUsers_LogonID"];?></td>
						</tr>
						<tr>
							<td>Posted On:</td>
							<td><?php echo date(' h:i:s A F j, Y', $row['timestamp']); ?></td>
						</tr>
					</table>
					<br/>
					<strong>Details</strong><br />
					<table style="padding: 10px;">
						<tr>
							<td>Make:</td>
							<td><?php echo $row["Make"]; 
								$carMake = $row["Make"];
							?></td>
						</tr>
						<tr>
							<td>Model:</td>
							<td><?php echo $row["Model"];
								$carModel = $row["Model"];
							?></td>
						</tr>
						<tr>
							<td>Vehicle Year:</td>
							<td><?php echo $row["VehicleYear"]; $carYear = $row["VehicleYear"]; ?></td>
						</tr>
						<tr>
							<td>Mileage:</td>
							<td><?php echo $row["Mileage"]; ?></td>
						</tr>
						<tr>
							<td>Exterior Color:</td>
							<td><?php echo $row["ExteriorColor"]; ?></td>
						</tr>
						<tr>
							<td>Engine:</td>
							<td><?php echo $row["Engine"]; $carEngine = $row["Engine"]; ?></td>
						</tr>
						<tr>
							<td>Driver Type:</td>
							<td><?php echo $row["DriverType"]; $carDrive = $row["DriverType"]; ?></td>
						</tr>
						<tr>
							<td>Number of Doors:</td>
							<td><?php echo $row["NoDoors"]; ?></td>
						</tr>
						<tr>
							<td>VIN:</td>
							<td><?php echo $row["VIN"]; ?></td>
						</tr>
					</table>
					<strong>Description</strong><br />
					<br />
					<?php echo stripslashes($row["Description"]); ?>
				</td>
			</tr>
		
		</table>
		
		<?php 
		if ($_SESSION["usertype"] == "regular")
		{
		?>
		<br /><br />
		<strong>You might also like...</strong>
		<?php
			//$query = "SELECT * FROM VehicleForSale WHERE Make = '$carMake' AND Model = '$carModel' AND VehicleForSaleID != $carId ORDER BY RAND() LIMIT 5";
			$query = "SELECT * FROM VehicleForSale";
			$result = $conn->query($query);
			if ($result->num_rows == 0) { echo "<br /><i>Whoops! This is a completely unique vehicle. You should snatch it up while you can!</i>"; }
			else {
				$scoreArray = array();
				while ($row = $result->fetch_assoc())
				{	
					$score = 0;
					if ($row["NonAdmins_AllUsers_LogonID"] == $carSeller)
					{
						$score += 1;
					}
					if ($row["Make"] == $carMake)
					{
						$score += 2;
					}
					if ($row["Model"] == $carModel)
					{
						$score += 2;
					}
					if ($row["VehicleYear"] == $carYear)
					{
						$score += 1;
					}
					if ($row["Engine"] == $carEngine)
					{
						$score += .5;
					}
					if ($row["DriverType"] == $carDrive)
					{
						$score += .5;
					}
					array_push($scoreArray, $score . "///" . $row["VehicleForSaleID"]);
				}
				sort($scoreArray);
				$reversedSort = array_reverse($scoreArray);
				$final = array_slice($reversedSort, 0, 4);
				$idString = "";
				foreach ($final as $topHit)
				{
					$a = explode("///", $topHit);
					$b = $a[1];
					$idString .= "VehicleForSaleID = " . $b . " OR ";
				}
				$idString = trim($idString, " OR ");
				$query = "SELECT * FROM VehicleForSale WHERE " . $idString;
				$result = $conn->query($query);
				echo "<table><tr>";
				while ($row = $result->fetch_assoc())
				{
					echo "<td style='padding:5px;'><a href='./viewCar.php?id=" . $row['VehicleForSaleID'] . "'><img src='./upload/" . $row['Photo'] . "' style='width:80px; height: 80px;' /></a><br />" . $row["Make"] . " " . $row["Model"] . " " . $row["VehicleYear"] . "<br />$" . $row["Price"] . "<br /><a href='./viewCar.php?id=" . $row['VehicleForSaleID'] . "'>See More</a></td>";
				}
				echo "</tr></table>";
			
			}
		}
		?>
		
		<br /><br />
		<strong>Comments</strong>
		<hr width="95%" /><br />		

	<?php

	// If we have a comment submission, update the database
	if (isset($_POST['submit']))
        {
		// Convert to MySQL datetime
		$timestampInSeconds = $_SERVER['REQUEST_TIME'];
		$mySqlDateTime = date("Y-m-d H:i:s", $timestampInSeconds);

		$conn = new mysqli($db_host, $db_user, $db_pword, $db_name);
		if ($conn->connect_error) {
			die('Error: Database connection problem: (' . $mysqli->connect_errno . ') ' . $mysqli->connect_error);
		}
		
		$user = $_SESSION["username"];
		$commenttext = $conn->real_escape_string($_POST['commenttext']);

		$query = "INSERT INTO Comments (RegisteredUser_NonAdmins_AllUsers_LogonID, VehicleForSale_VehicleForSaleID, CommentTime, CommentText) ";
		$query .= "VALUES ('$user', '$id', '$mySqlDateTime', '$commenttext')";

		$result = $conn->query($query);

		if ($conn->error != "")
		{
			die("Error: query error. " . $mysqli->error . " " . $query);
		}

        }
		
		$query = "SELECT * FROM Comments WHERE VehicleForSale_VehicleForSaleID = ". $id . " ORDER BY CommentTime DESC";
		?>

	<?php
		if ( $_SESSION["usertype"] == "dealer" || $_SESSION["usertype"] == "regular" )
		{
		
	?>

		<form method="post" action="viewCar.php?id=<?php echo $id; ?>" enctype="multipart/form-data">
		<textarea name="commenttext" id="commenttext" rows="5" cols="75"></textarea><br />
		<input type="submit" value="Submit" name="submit" id="submit" />

		</form>
		<br /><br />
	<?php
		}

	if ($result = $conn->query($query))
	{
		while ($row = $result->fetch_assoc())
		{
	?>
		<br />
		<table style="padding: 3px;">
			
			<tr>
				<td>Posted by <font color="blue"><?php echo $row["RegisteredUser_NonAdmins_AllUsers_LogonID"]; ?></font> -
				<?php echo date("g:i a F j, Y ", strtotime($row["CommentTime"])); ?></td>
			</tr>
			<tr>
				<td>&nbsp;&nbsp;<?php echo stripslashes($row["CommentText"]); ?></td>
			</tr>
		</table>
		<br />

	<?php
		}
	}
	else
	{
		echo "<br />No comments posted.<br />";
	}
	} // end !isset($_POST['delete'])
	?>

		

	
 </div>	
	<script type="text/javascript">
	
	function send(actionType) {
	
		// 1 - send notification
		// 2 - send bookmark
		var vId = "<?php echo $carId; ?>";
		var uId = "<?php echo $_SESSION['username']; ?>";
		$.ajax({
		   type: "POST",
		   url: "sendNotification.php",
		   data: "id=" + vId + "&user=" + uId + "&act=" + actionType,
		   success: function(msg){
			 alert( msg);
		   }
		 });
	
	}
	</script>

<?php include("inc_footer.php"); ?>
